package com.ctgu.admin.system.controller;

import com.ctgu.admin.system.domain.Article;
import com.ctgu.admin.system.domain.Comment;
import com.ctgu.admin.system.domain.Information;
import com.ctgu.admin.system.domain.Payment;
import com.ctgu.admin.system.service.ArticleService;
import com.ctgu.admin.system.service.CommentService;
import com.ctgu.admin.system.service.EmailService;
import com.ctgu.admin.system.service.InformationService;
import com.ctgu.admin.system.validator.ArticleValid;
import com.ctgu.common.constant.StatusConst;
import com.ctgu.common.enums.StatusEnum;
import com.ctgu.common.utils.EntityBeanUtil;
import com.ctgu.common.utils.ResultVoUtil;
import com.ctgu.common.utils.StatusUtil;
import com.ctgu.common.vo.ResultVo;
import com.ctgu.component.shiro.ShiroUtil;
import com.ctgu.modules.system.domain.User;
import com.ctgu.modules.system.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 评论的控制层
 */
@Controller
@RequestMapping("/system/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private UserService userService;

    @Autowired
    private InformationService informationService;

    @Autowired
    private EmailService emailService;
    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("system:article:index")
    public String index(Model model, Article article) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("title", match -> match.contains())
                .withMatcher("content", match -> match.contains());

        // 获取数据列表
        Example<Article> example = Example.of(article, matcher);
        Page<Article> list = articleService.getPageList(example);



        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/system/article/index";
    }

    /**
     * 跳转到用户的编辑文章界面
     */
    @GetMapping("/editArticle/{id}")
    public String toArticleEdit(@PathVariable("id") Article article, Model model){
        User user = ShiroUtil.getSubject();
        model.addAttribute("user",user);
        model.addAttribute("author",article.getCreateBy());
        model.addAttribute("article",article);
        return "/submission/articleEdit";
    }

    /**
     * 通过某一篇文章
     */
    @GetMapping("/pass")
    @ResponseBody
    public Map<String,String> passArticleByID(@RequestParam("articleID")Long ID,
                                              @RequestParam("flag")Boolean flag){
        Article article = articleService.getById(ID);
        Map<String,String> result = new HashMap<String,String>();
        //给用户发送一条审核消息
        Information information = new Information();
        information.setTitle("审核消息");
        information.setCreateDate(new Date());
        information.setUpdateDate(new Date());
        information.setUserID(article.getCreateBy().getId());
        information.setStatus((byte)0);
        String content = "";
        if(article!=null){
            if(flag){
                article.setStatus(StatusEnum.PASS.getCode());
                result.put("msg","该文章已审核成功！");
                content = "您的稿件'" + article.getTitle() + "'已被审核通过";
            }
            else{
                article.setStatus(StatusEnum.NOT_PASS.getCode());//审核不通过的选项
                result.put("msg","该文章已成功打回！");
                content = "您的稿件'" + article.getTitle() + "'审核未通过,请检查您的稿件内容";
            }
            //保存信息
            information.setContent(content);
            informationService.save(information);
            //发送邮件提醒
            emailService.sendAttachmentMail(article.getCreateBy().getEmail(),"来自《读者出版社》的通知消息：",content);

            articleService.save(article);
            return result;
        }else{
            result.put("msg","通过文章失败,可能文章已被删除");
            return result;
        }
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("system:article:add")
    public String toAdd() {
        return "/system/article/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("system:article:edit")
    public String toEdit(@PathVariable("id") Article article, Model model) {
        model.addAttribute("article", article);
        return "/system/article/add";
    }

    /**
     * 保存添加/修改的数据
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"system:article:add", "system:article:edit"})
    @ResponseBody
    public ResultVo save(@Validated ArticleValid valid, Article article) {
        // 复制保留无需修改的数据
        if (article.getId() != null) {
            Article beArticle = articleService.getById(article.getId());
            EntityBeanUtil.copyProperties(beArticle, article);
        }

        // 保存数据
        articleService.save(article);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面，这个是后台中的详细界面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("system:article:detail")
    public String toDetail(@PathVariable("id") Article article, Model model) {
        model.addAttribute("article",article);
        return "/system/article/detail";
    }

    /**
     * 跳转到用户可看的文章界面，这个是所有人都可以阅读的界面
     */
    @GetMapping("/read/{id}")
    public String toArticle(@PathVariable("id") Long article_id, Model model) {
        User user = ShiroUtil.getSubject();
        Article article = articleService.getById(article_id);

        List<Comment> comments = commentService.getAllByArticleID(article_id);

        model.addAttribute("article",article);
        model.addAttribute("commentList",comments);
        model.addAttribute("user",user);
        return "/submission/articleDetail";
    }


    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("system:article:status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (articleService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
}